package me.lwn.auth.resources;

import me.lwn.auth.security.utils.Constants;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    private final RegisteredClientRepository repository;

    public LoginController(RegisteredClientRepository repository) {
        this.repository = repository;
    }

    @GetMapping("login")
    public String login(HttpServletRequest request, HttpServletResponse response) {

        String prefix = "default";
        HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        String[] clientIds = savedRequest.getParameterValues(OAuth2ParameterNames.CLIENT_ID);
        if (clientIds != null && clientIds.length > 0) {
            RegisteredClient registeredClient = repository.findByClientId(clientIds[0]);
            if (registeredClient != null) {
                Boolean captcha = registeredClient.getClientSettings().getSetting(Constants.ClientSetting.REQUIRE_CAPTCHA.getKey());
                request.getSession(false).setAttribute(Constants.ClientSetting.REQUIRE_CAPTCHA.getKey(), captcha != null && captcha);
                Boolean customizerLoginPage = registeredClient.getClientSettings().getSetting(Constants.ClientSetting.CUSTOMIZE_LOGIN_PAGE.getKey());
                if (customizerLoginPage != null && customizerLoginPage) {
                    prefix = clientIds[0];
                }
            }
        }
        return prefix + "/login";
    }
}
